package com.insigma.yanwenlong.bookkeeping.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.insigma.yanwenlong.bookkeeping.db.jdbc.DBConnection;
import com.insigma.yanwenlong.bookkeeping.pojo.Type;

public class TypeDaoImpl implements TypeDao {

	@Override
	public List<Type> findAllBigTypes(int direction) throws SQLException {
		Connection connection = DBConnection.getConnection();
		String sql = "select * from type where direction = ? and parentId = 0";
		PreparedStatement preparedStatement = connection.prepareStatement(sql);
		preparedStatement.setString(1, (direction == 1)?"支出":"收入");
		ResultSet resultSet = preparedStatement.executeQuery();
		
		List<Type> types = new ArrayList<Type>();
		while(resultSet.next()) {
			Type type = new Type();
			type.setId(resultSet.getInt("id"));
			type.setDirection(resultSet.getString("direction"));
			type.setName(resultSet.getString("name"));
			type.setParentId(resultSet.getInt("parentId"));
			types.add(type);
		}
		
		DBConnection.closeResultSet(resultSet);
		DBConnection.closeStatement(preparedStatement);
		DBConnection.closeConnection(connection);
		
		return types;
	}

	@Override
	public List<Type> findAllSmallTypes(int id,int direction) throws SQLException {
		Connection connection = DBConnection.getConnection();
		String sql = "select * from type where parentId = ? and direction = ?";
		PreparedStatement preparedStatement = connection.prepareStatement(sql);
		preparedStatement.setInt(1, id);
		preparedStatement.setString(2, (direction == 1)?"支出":"收入");
		ResultSet resultSet = preparedStatement.executeQuery();
		
		List<Type> types = new ArrayList<Type>();
		while(resultSet.next()) {
			Type type = new Type();
			type.setId(resultSet.getInt("id"));
			type.setDirection(resultSet.getString("direction"));
			type.setName(resultSet.getString("name"));
			type.setParentId(resultSet.getInt("parentId"));
			types.add(type);
		}
		
		DBConnection.closeResultSet(resultSet);
		DBConnection.closeStatement(preparedStatement);
		DBConnection.closeConnection(connection);
		
		return types;
	}

}
